<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户端 - 即时通信系统</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 1.8em;
            margin-bottom: 10px;
        }
        
        .status {
            font-size: 0.9em;
            opacity: 0.9;
        }
        
        .main-content {
            padding: 30px;
        }
        
        .connection-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
        }
        
        .input-group {
            margin-bottom: 15px;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        
        .input-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }
        
        .input-group input:focus {
            outline: none;
            border-color: #4CAF50;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
        }
        
        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.3);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
        }
        
        .connection-status {
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: bold;
        }
        
        .status-disconnected {
            background: #ffebee;
            color: #c62828;
        }
        
        .status-connecting {
            background: #fff3e0;
            color: #ef6c00;
        }
        
        .status-connected {
            background: #e8f5e8;
            color: #2e7d32;
        }
        
        .status-waiting {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 1.5em;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* 聊天弹窗样式 */
        .chat-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .chat-modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .chat-window {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            animation: slideIn 0.3s ease;
        }
        
        .chat-header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 15px 20px;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .chat-header h3 {
            margin: 0;
            font-size: 1.2em;
        }
        
        .close-btn {
            background: none;
            border: none;
            color: white;
            font-size: 1.5em;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.3s;
        }
        
        .close-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .chat-body {
            flex: 1;
            padding: 20px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .chat-messages {
            flex: 1;
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            overflow-y: auto;
            background: #fafafa;
            margin-bottom: 15px;
            max-height: 300px;
        }
        
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 8px;
            max-width: 80%;
        }
        
        .message.system {
            background: #e3f2fd;
            color: #1976d2;
            text-align: center;
            margin: 10px auto;
        }
        
        .message.received {
            background: #f1f1f1;
            color: #333;
            align-self: flex-start;
        }
        
        .message.sent {
            background: #4CAF50;
            color: white;
            align-self: flex-end;
            margin-left: auto;
        }
        
        .message-header {
            font-size: 0.8em;
            opacity: 0.7;
            margin-bottom: 5px;
        }
        
        .chat-input {
            display: flex;
            gap: 10px;
        }
        
        .chat-input input {
            flex: 1;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
        }
        
        .chat-input input:focus {
            outline: none;
            border-color: #4CAF50;
        }
        
        .chat-input .btn {
            margin: 0;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        /* 聊天按钮 */
        .chat-toggle-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
            transition: all 0.3s ease;
            z-index: 999;
        }
        
        .chat-toggle-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
        }
        
        .chat-toggle-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        @media (max-width: 600px) {
            .main-content {
                padding: 20px;
            }
            
            .chat-input {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                margin-right: 0;
            }
            
            .chat-window {
                width: 95%;
                max-height: 90vh;
            }
            
            .chat-toggle-btn {
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                font-size: 1.2em;
            }
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="window.location.href='http://10.8.20.95:8080/'">←</button>
    
    <div class="container">
        <div class="header">
            <h1>客户端</h1>
            <div class="status" id="connectionStatus">正在连接...</div>
        </div>
        
        <div class="main-content">
            <div class="connection-section">
                <div class="section-title">连接管理</div>
                
                <div class="input-group">
                    <label for="clientName">您的姓名：</label>
                    <input type="text" id="clientName" placeholder="请输入您的姓名" value="客户端用户">
                </div>
                
                <div class="connection-status" id="statusDisplay">
                    <span id="statusText">未连接</span>
                </div>
                
                <button class="btn btn-primary" id="connectBtn" onclick="requestConnection()">
                    申请连接
                </button>
                <button class="btn btn-secondary" id="disconnectBtn" onclick="disconnect()" disabled>
                    断开连接
                </button>
            </div>
        </div>
    </div>
    
    <!-- 聊天弹窗 -->
    <div class="chat-modal" id="chatModal">
        <div class="chat-window">
            <div class="chat-header">
                <h3>聊天窗口</h3>
                <button class="close-btn" onclick="closeChatWindow()">×</button>
            </div>
            <div class="chat-body">
                <div class="chat-messages" id="chatMessages">
                    <div class="message system">
                        等待连接建立...
                    </div>
                </div>
                <div class="chat-input">
                    <input type="text" id="messageInput" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
                    <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 聊天按钮 -->
    <button class="chat-toggle-btn" id="chatToggleBtn" onclick="toggleChatWindow()" disabled>
        💬
    </button>
    
    <script>
        let socket = null;
        let isConnected = false;
        let isWaiting = false;
        let isChatWindowOpen = false;
        let connectionCheckInterval = null; // 添加定时器变量
        
        // 初始化WebSocket连接
        function initWebSocket() {
            console.log('开始初始化WebSocket连接...');
            
            // 清理之前的定时器
            if (connectionCheckInterval) {
                clearInterval(connectionCheckInterval);
                connectionCheckInterval = null;
            }
            
            socket = new SockJS('http://10.8.20.95:8080/ws?type=client');
            
            socket.onopen = function() {
                console.log('WebSocket连接已建立，状态:', socket.readyState);
                console.log('连接URL:', socket._transport.url);
                updateStatus('connected', 'WebSocket连接已建立');
                document.getElementById('connectionStatus').textContent = '已连接';
                
                // 定期检查连接状态
                connectionCheckInterval = setInterval(() => {
                    console.log('当前WebSocket状态:', socket.readyState);
                    if (socket.readyState !== 1) {
                        console.log('WebSocket连接已断开，状态:', socket.readyState);
                        updateStatus('disconnected', '连接已断开');
                        // 清理定时器
                        if (connectionCheckInterval) {
                            clearInterval(connectionCheckInterval);
                            connectionCheckInterval = null;
                        }
                    }
                }, 5000);
            };
            
            socket.onmessage = function(event) {
                console.log('收到WebSocket消息:', event.data);
                const message = JSON.parse(event.data);
                handleMessage(message);
            };
            
            socket.onclose = function(event) {
                console.log('WebSocket连接关闭:', event);
                console.log('关闭代码:', event.code);
                console.log('关闭原因:', event.reason);
                updateStatus('disconnected', '连接已断开');
                document.getElementById('connectionStatus').textContent = '连接断开';
                isConnected = false;
                isWaiting = false;
                closeChatWindow();
                
                // 清理定时器
                if (connectionCheckInterval) {
                    clearInterval(connectionCheckInterval);
                    connectionCheckInterval = null;
                }
            };
            
            socket.onerror = function(error) {
                console.error('WebSocket错误:', error);
                updateStatus('disconnected', '连接错误');
                
                // 清理定时器
                if (connectionCheckInterval) {
                    clearInterval(connectionCheckInterval);
                    connectionCheckInterval = null;
                }
            };
        }
        
        // 处理接收到的消息
        function handleMessage(message) {
            console.log('收到消息:', message);
            
            switch(message.type) {
                case 'SYSTEM_MESSAGE':
                    if (isChatWindowOpen) {
                        addSystemMessage(message.content);
                    }
                    break;
                    
                case 'CONNECT_ACCEPT':
                    isConnected = true;
                    isWaiting = false;
                    updateStatus('connected', '连接已建立');
                    addSystemMessage('连接已建立，可以开始聊天！');
                    // 自动打开聊天窗口
                    if (!isChatWindowOpen) {
                        openChatWindow();
                    }
                    break;
                    
                case 'CONNECT_REJECT':
                    isWaiting = false;
                    updateStatus('disconnected', '连接被拒绝');
                    // 先关闭聊天窗口
                    closeChatWindow();
                    // 显示页面提示
                    alert('连接请求被拒绝，请稍后重试');
                    break;
                    
                case 'CONNECT_RELEASE':
                    isConnected = false;
                    updateStatus('disconnected', '连接已释放');
                    // 关闭聊天窗口，不在聊天窗口中添加系统消息
                    closeChatWindow();
                    break;
                    
                case 'CHAT_MESSAGE':
                    addChatMessage(message.content, message.from, false);
                    // 如果聊天窗口未打开，自动打开
                    if (!isChatWindowOpen) {
                        openChatWindow();
                    }
                    break;
            }
        }
        
        // 申请连接
        function requestConnection() {
            const clientName = document.getElementById('clientName').value.trim();
            if (!clientName) {
                alert('请输入您的姓名');
                return;
            }
            
            console.log('开始申请连接，客户端名称:', clientName);
            
            // 如果已有连接，先关闭
            if (socket) {
                socket.close();
                socket = null;
            }
            
            // 重置状态
            isConnected = false;
            isWaiting = false;
            closeChatWindow();
            
            // 更新状态
            updateStatus('disconnected', '正在建立连接...');
            
            // 创建WebSocket连接
            initWebSocket();
            
            // 等待连接建立后发送请求
            const checkConnection = setInterval(() => {
                if (socket && socket.readyState === 1) {
                    clearInterval(checkConnection);
                    console.log('WebSocket连接已建立，发送连接请求');
                    sendConnectionRequest(clientName);
                } else if (socket && socket.readyState === 3) {
                    // 连接已关闭，停止检查
                    clearInterval(checkConnection);
                    console.log('WebSocket连接失败');
                    updateStatus('disconnected', '连接失败，请重试');
                    alert('连接失败，请重试');
                }
            }, 100);
            
            // 设置超时，避免无限等待
            setTimeout(() => {
                clearInterval(checkConnection);
                if (!socket || socket.readyState !== 1) {
                    console.log('连接超时');
                    updateStatus('disconnected', '连接超时，请重试');
                    alert('连接超时，请重试');
                }
            }, 10000); // 10秒超时
        }
        
        // 发送连接请求的辅助函数
        function sendConnectionRequest(clientName) {
            const message = {
                type: 'CONNECT_REQUEST',
                from: clientName,
                content: '申请连接'
            };
            
            console.log('发送连接请求:', message);
            console.log('WebSocket状态:', socket.readyState);
            
            try {
                socket.send(JSON.stringify(message));
                isWaiting = true;
                updateStatus('waiting', '等待服务端用户处理...');
                // 不在聊天窗口中添加系统消息，只在页面上显示状态
            } catch (error) {
                console.error('发送消息失败:', error);
                alert('发送消息失败，请重试');
            }
        }
        
        // 断开连接
        function disconnect() {
            if (socket) {
                // 重置状态变量
                isConnected = false;
                isWaiting = false;
                closeChatWindow();
                
                // 关闭WebSocket连接
                socket.close();
                
                // 重新初始化WebSocket连接
                setTimeout(() => {
                    initWebSocket();
                }, 1000); // 延迟1秒重新连接
            }
        }
        
        // 发送消息
        function sendMessage() {
            if (!isConnected) {
                alert('未建立连接，无法发送消息');
                return;
            }
            
            const input = document.getElementById('messageInput');
            const content = input.value.trim();
            
            if (!content) {
                return;
            }
            
            const message = {
                type: 'CHAT_MESSAGE',
                from: document.getElementById('clientName').value.trim(),
                content: content
            };
            
            socket.send(JSON.stringify(message));
            addChatMessage(content, '我', true);
            input.value = '';
        }
        
        // 处理回车键
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }
        
        // 更新状态显示
        function updateStatus(status, text) {
            const statusDisplay = document.getElementById('statusDisplay');
            const statusText = document.getElementById('statusText');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            const chatToggleBtn = document.getElementById('chatToggleBtn');
            
            statusDisplay.className = 'connection-status status-' + status;
            statusText.textContent = text;
            
            switch(status) {
                case 'disconnected':
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    chatToggleBtn.disabled = true;
                    break;
                case 'waiting':
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    chatToggleBtn.disabled = true;
                    break;
                case 'connected':
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = false;
                    chatToggleBtn.disabled = false;
                    break;
            }
        }
        
        // 打开聊天窗口
        function openChatWindow() {
            const modal = document.getElementById('chatModal');
            modal.classList.add('show');
            isChatWindowOpen = true;
            // 聚焦到输入框
            setTimeout(() => {
                document.getElementById('messageInput').focus();
            }, 100);
        }
        
        // 关闭聊天窗口
        function closeChatWindow() {
            const modal = document.getElementById('chatModal');
            modal.classList.remove('show');
            isChatWindowOpen = false;
        }
        
        // 切换聊天窗口
        function toggleChatWindow() {
            if (isChatWindowOpen) {
                closeChatWindow();
            } else {
                openChatWindow();
            }
        }
        
        // 点击模态框背景关闭
        document.getElementById('chatModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeChatWindow();
            }
        });
        
        // 添加系统消息
        function addSystemMessage(content) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message system';
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 添加聊天消息
        function addChatMessage(content, sender, isSent) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;
            
            const headerDiv = document.createElement('div');
            headerDiv.className = 'message-header';
            headerDiv.textContent = sender + ' - ' + new Date().toLocaleTimeString();
            
            const contentDiv = document.createElement('div');
            contentDiv.textContent = content;
            
            messageDiv.appendChild(headerDiv);
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('客户端页面初始化...');
            
            // 检查是否是页面刷新
            const isPageRefresh = performance.navigation.type === 1 || 
                                (window.performance && window.performance.getEntriesByType('navigation')[0] && 
                                 window.performance.getEntriesByType('navigation')[0].type === 'reload');
            
            if (isPageRefresh) {
                console.log('检测到页面刷新，清理可能的状态残留...');
                
                // 清理localStorage中可能的状态
                localStorage.removeItem('clientConnected');
                localStorage.removeItem('clientWaiting');
                localStorage.removeItem('clientSessionId');
                
                // 清理sessionStorage
                sessionStorage.clear();
            }
            
            // 初始化状态显示
            updateStatus('disconnected', '未连接');
            
            // 添加页面卸载时的清理
            window.addEventListener('beforeunload', function() {
                console.log('页面即将卸载，清理连接...');
                if (socket) {
                    socket.close();
                }
                if (connectionCheckInterval) {
                    clearInterval(connectionCheckInterval);
                }
            });
        });
    </script>
</body>
</html> 
